<template>
  <div class="payList">

    <avue-crud :option="option"
               :data="list"
               :page="page"
               :row-style="rowStyle"
               :cell-style="cellStyle"
               @search-change="searchChange"
               @row-dblclick="handleRowDBLClick"
               @size-change="sizeChange"
               @current-change="currentChange"
               @refresh-change="refreshChange">
      <template slot="header">
        <avue-data-box :option="dataOption"></avue-data-box>
      </template>
      <template slot="menuLeft">
        <el-button type="primary"
                   @click="handleTime"
                   :icon="time==0?'el-icon-help':'el-icon-s-help'"
                   size="small">{{time==0?'刷 新':'停 止'}}</el-button>
        <el-button type="danger"
                   :icon="el-icon-document"
                   @click="$router.push({path:'/fp'})"
                   size="small">发票管理
        </el-button>
      </template>
      <template slot-scope="scope"
                slot="type">
        <img width="30"
             :src="scope.row.type === 0 ? '/images/zfbicon.png' : ' /images/wxicon.png'">
      </template>
      <template slot="menu"
                slot-scope="scope">
        <el-button v-if="[3,5,10].includes(scope.row.version)"
                   @click="handleFp(scope.row)"
                   type="text"
                   size="mini">发票</el-button>
        <template v-if="!scope.row.flag">
          <el-button type="text"
                     @click="handleOk(scope.row)"
                     size="small">开通</el-button>

          <el-button type="text"
                     @click="handleDel(scope.row)"
                     size="small">删除</el-button>
        </template>
        <template v-else>
          <el-button type="text"
                     @click="handleReset(scope.row)"
                     size="small">补单</el-button>
        </template>
      </template>
    </avue-crud>
    <el-dialog title="发票信息"
               top="40px"
               :before-close="beforeClose"
               :visible.sync="fpbox"
               width="400px">
      <avue-form :option="fpoption"
                 @submit="fpSubmit"
                 v-model="fpform">
        <template slot="compid"
                  slot-scope="{}">
          <el-input placeholder="请输入编号"
                    v-model="fpform.compid">
            <div slot="append"
                 @click="buildId">自动生成编号</div>

          </el-input>
        </template>
        <template slot="menuForm">
          <el-button @click="fpBuild">生成授权书</el-button>
        </template>
      </avue-form>
    </el-dialog>
    <auth ref="auth"
          @submit="getList">
    </auth>
  </div>
</template>

<script>
function getType (type) {
  let result = '';
  if ([2, 3].includes(type)) {
    result = "avue-cli";
  } if (type == 0) {
    result = "avuex";
  } else if (type == 1) {
    result = "avuex-data";
  } else {
    result = "avue-cli";
  }
  return result
}
import { config, payList } from './config'
export default {
  data () {
    return {
      moneyData: [],
      page: {
        currentPage: 1,
        total: 0,
        pageSizes: [10, 30, 50, 100, 200, 1000],
        pageSize: 10
      },
      check: 0,
      time: 0,
      fpbox: false,
      fpform: {
        qq: ''
      },
      fpoption: {
        size: 'mini',
        emptyBtn: false,
        column: [{
          label: '订单号',
          prop: 'orderid',
          disabled: true,
          span: 24
        }, {
          label: '编号',
          prop: 'compid',
          formslot: true,
          span: 24
        }, {
          label: '公司名称',
          prop: 'mc',
          rules: [{
            required: true,
            message: "请输入公司名称",
            trigger: "blur"
          }],
          span: 24
        }, {
          label: '曾用名',
          prop: 'cym',
          span: 24
        }, {
          label: '公司税号',
          prop: 'sh',
          span: 24
        }, {
          label: '收件人',
          prop: 'sjr',
          span: 24
        }, {
          label: '联系方式',
          span: 24,
          prop: 'lxfs',
        }, {
          label: '收件地址',
          prop: 'sjdz',
          type: 'textarea',
          span: 24
        }]
      },
      option: {
        size: 'mini',
        excelBtn: true,
        selection: true,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        index: true,
        translate: false,
        headerAlign: 'center',
        align: 'center',
        showSummary: true,
        menuAlign: 'left',
        sumColumnList: [
          {
            name: 'money',
            type: 'sum'
          },
          {
            name: 'version',
            type: 'count'
          }
        ],
        defaultSort: {
          prop: 'datetime',
          order: 'descending'
        },
        column: [
          {
            label: '订单号',
            prop: 'orderid',
            search: true,
            width: 160,
          }, {
            label: '套餐名',
            prop: 'version',
            type: 'select',
            dicData: config,
            filter: true,
          }, {
            label: '金额',
            prop: 'money'
          }, {
            label: '备注QQ',
            prop: 'qq',
            search: true
          }, {
            label: '支付类型',
            prop: 'type',
            type: 'select',
            slot: true,
            dicData: payList,
            filter: true,
          }, {
            label: '状态',
            prop: 'flag',
            type: 'select',
            filter: true,
            dicData: [{
              label: '已付款',
              value: true
            }, {
              label: '未付款',
              value: false
            }]
          }, {
            label: '下单日期',
            sortable: true,
            type: 'date',
            valueFormat: 'yyyy-MM-dd',
            format: 'yyyy-MM-dd',
            prop: 'datetime'
          }
        ]
      },
      list: [],
    }
  },
  computed: {
    dataOption () {
      return {
        span: 4,
        data: [
          {
            title: '总单数',
            count: this.moneyData[0] || 0,
            icon: 'el-icon-s-check',
            color: '#1494E3',
            target: '_blank'
          },
          {
            title: '总金额',
            count: this.moneyData[1] || 0,
            icon: 'el-icon-s-order',
            color: '#E6A23C',
            target: '_blank'
          }, {
            title: '上月金额',
            count: this.moneyData[2] || 0,
            icon: 'el-icon-view',
            color: 'rgb(56, 161, 242)',
            target: '_blank'
          },
          {
            title: '本月金额',
            count: this.moneyData[3] || 0,
            icon: 'el-icon-setting',
            color: 'rgb(117, 56, 199)',
            target: '_blank'
          },
          {
            title: '今日金额',
            count: this.moneyData[4] || 0,
            icon: 'el-icon-tickets',
            color: '#F56C6C',
            target: '_blank'
          },
          {
            title: '今日单数',
            count: this.moneyData[5] || 0,
            icon: 'el-icon-user',
            color: 'rgb(97, 60, 189)',
            target: '_blank'
          },
        ]
      }
    }
  },
  methods: {
    searchChange (params, done) {
      done();
      this.getList(params);
    },
    handleRowDBLClick (row) {
      this.handleReset(row);
    },
    buildId () {
      const query = this.Bmob.Query("ticket");
      query.equalTo("special", "!=", true);
      query.equalTo("compid", "!=", '');
      query.order("-datetime", "-compid");
      query.limit(1)
      query.find().then(res => {
        const key = 'A', len = 5;
        let id = Number(res[0].compid.replace(/[^0-9]/ig, "")) + 1;
        let length = len - (id + '').length;
        let result = '';
        for (let i = 0; i < length; i++) {
          result = result + '0'
        }
        result = key + result + id;
        this.fpform.compid = result;
        this.$message.success('生成成功')
      });

    },
    getMoneyData () {
      let query = this.Bmob.Query("order");
      const date = new Date();
      let month = date.getMonth() + 1; month = month < 10 ? '0' + month : month
      let lastmonth = date.getMonth(); lastmonth = lastmonth < 10 ? '0' + lastmonth : lastmonth
      let year = date.getFullYear();
      //总订单
      query = this.Bmob.Query("order");
      query.equalTo("flag", "==", true);
      query.count().then(res => {
        this.$set(this.moneyData, 0, res)
      })
      // 总金额
      query.equalTo("flag", "==", true);
      query.statTo("sum", "money");
      query.find().then(res => {
        this.$set(this.moneyData, 1, res[0]._sumMoney)
      });
      //上月金额
      query = this.Bmob.Query("order");
      query.equalTo("datetime", ">=", `${year}-${lastmonth}-01`);
      query.equalTo("datetime", "<=", `${year}-${lastmonth}-31`);
      query.equalTo("flag", "==", true);
      query.statTo("sum", "money");
      query.find().then(res => {
        this.$set(this.moneyData, 2, res[0]._sumMoney)
      });
      //本月金额
      query = this.Bmob.Query("order");
      query.equalTo("datetime", ">=", `${year}-${month}-01`);
      query.equalTo("datetime", "<=", `${year}-${month}-31`);
      query.equalTo("flag", "==", true);
      query.statTo("sum", "money");
      query.find().then(res => {
        this.$set(this.moneyData, 3, res[0]._sumMoney)
      });
      //今日金额
      query = this.Bmob.Query("order");
      query.equalTo("datetime", ">", new Date().Format('yyyy-MM-dd'));
      query.equalTo("flag", "==", true);
      query.statTo("sum", "money");
      query.find().then(res => {
        if (res[0]) {
          this.$set(this.moneyData, 4, res[0]._sumMoney)
        }
      });
      //今日订单
      query = this.Bmob.Query("order");
      query.equalTo("flag", "==", true);
      query.equalTo("datetime", ">", new Date().Format('yyyy-MM-dd'));
      query.count().then(res => {
        this.$set(this.moneyData, 5, res)
      })
    },
    currentChange (val) {
      this.page.currentPage = val
      this.getList()
    },
    insert (data, table) {
      const query = this.Bmob.Query(table || 'order');
      data.cym = data.cym || ''
      Object.keys(data).forEach(ele => {
        if (ele.includes('$')) {
          query.set(ele.replace('$', '') + '_text', data[ele])
        } else {
          query.set(ele, data[ele])
        }

      })
      return query.save()
    },
    fpBuild () {
      const { href } = this.$router.resolve({
        path: '/sqs',
        query: {
          qq: this.fpform.qq,
          id: this.fpform.compid,
          name: this.fpform.mc,
          date: this.fpform.datetime
        }
      })
      window.open(href, '_blank')
    },
    fpSubmit (form, done) {
      form = this.deepClone(this.fpform);
      if (!form.datetime) form.datetime = (new Date()).Format('yyyy.MM.dd');
      if (this.fpform.objectId) {
        this.update(form.objectId, form, 'ticket').then(() => {
          done();
          this.$message.success('发票修改成功')
        }).catch(() => {
          done();
        })
      } else {
        this.insert(form, 'ticket').then(() => {
          done();
          this.$message.success('发票新增成功')
        }).catch(() => {
          done();
        })
      }

    },
    beforeClose (done) {
      this.$set(this.fpform, {})
      done()
    },
    handleFp (row = {}) {
      const query = this.Bmob.Query("ticket");
      query.equalTo("orderid", "==", row.orderid);
      query.find().then(res => {
        this.fpform = res[0] || {};
        if (this.validatenull(this.fpform)) {
          this.fpform.orderid = row.orderid;
        }
        this.fpbox = true
        this.fpform.qq = row.qq;
      });
    },
    update (id, data, table) {
      const form = this.deepClone(data);
      const query = this.Bmob.Query(table || 'order');
      query.set('id', id)
      delete form.createdAt;
      delete form.updatedAt;
      delete form.objectId;
      Object.keys(form).forEach(ele => {
        if (form[ele]) {
          query.set(ele, form[ele]) //需要修改的objectId
        }

      })
      return query.save()
    },
    del (id) {
      const query = this.Bmob.Query('order');
      return query.destroy(id)
    },
    rowStyle ({ row }) {
      if (!row.flag) {
        return {
          backgroundColor: 'rgba(245,108,108,0.1)'
        }
      }
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize;
      this.getList();
    },
    cellStyle ({ row, columnIndex }) {
      if (columnIndex == 6) {
        return Object.assign((() => {
          return { color: row.type === 0 ? '#409EFF' : 'green', }
        })(), {
          fontWeight: 'bold',
          fontSize: '20'
        })

      } else if (columnIndex == 7) {
        if (!row.flag) {
          return {
            color: 'red',
            fontWeight: 'bold',
            fontSize: '20'
          }
        }
      } else if (columnIndex == 2) {
        return {
          color: '#333',
          fontWeight: 'bold',
          fontSize: '20'
        }
      }
    },
    handleDel (row) {
      this.$confirm(`是否删除【${row.qq}】的【${row.name}】订单`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return this.del(row.objectId)
      }).then(() => {
        this.list.splice(row.$index, 1);
        this.$message.success('删除成功')
      })
    },
    handleReset (row) {
      this.$confirm(`是否补【${row.qq}】的【${row.name}】订单`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let type = getType(row.version);
        return this.$httpajax.get(this.website.GIT.url.replace('${qq}', row.qq).replace('${type}', type))
          .then((res) => {
            this.$alert(`${res.data}`, '提示', {
              confirmButtonText: '确定',
            });
          })
      })
    },
    handleOk (row) {
      this.$confirm(`是否更新【${row.qq}】的【${row.name}】权限`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.flag = true
        return this.update(row.objectId, {
          flag: true
        })
      }).then(() => {
        return this.$confirm(`是否开通【${row.qq}】的【${row.name}】】权限`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      }).then(() => {
        this.handleReset(row);
      })
    },
    handleTime () {
      if (this.time == 0) {
        this.time = 1000;
        this.check = setInterval(() => {
          this.getList()
        }, this.time);

      } else {
        this.time = 0;
        clearInterval(this.check)
      }
    },
    refreshChange () {
      this.list = [];
      this.$message.success('刷新成功')
      this.getList();
    },
    getList (params = {}) {
      if (!this.$refs.auth.flag) return
      const query = this.Bmob.Query("order");
      query.count().then(res => {
        this.page.total = res;
        const next = (this.page.currentPage - 1) * this.page.pageSize;
        const breaks = this.page.pageSize * this.page.currentPage;
        query.limit(breaks)
        query.skip(next)
        for (let o in params) {
          query.equalTo(o, "==", params[o]);
        }
        query.order("-datetime");
        return query.find()
      }).then(res => {
        this.list = res;
      });
      this.getMoneyData();

    }
  }
}
</script>

<style lang="scss">
.payList {
  padding-top: 80px;
  min-height: 700px;
}
</style>
